<template>
  <div class="CharacterBgc">
    <!-- 添加角色按钮 -->
    <div class="ChaHeader">
      <el-button type="primary" class="addCharactor" @click="formShow = true"
        >添加角色</el-button
      >
    </div>
    <!-- 展示界面 -->
    <div class="ChaContent">
      <el-table :data="tableData" border style="width: 100%" height="98%">
        <el-table-column type="expand" label="权限明细" width="100px">
          <template slot-scope="scope">
            <f-form label-position="left" inline class="demo-table-expand">
              <el-tag
                v-for="tag in scope.row.assign"
                :key="tag.resourceId"
                closable
                :disable-transitions="false"
                :type="tag.resourceId"
                @close="handleClose(tag, scope.row)"
                class="assignTag"
              >
                {{ tag.resourceName }}
              </el-tag>
            </f-form>
          </template>
        </el-table-column>
        <el-table-column label="序号" prop="roleId" width="80" align="center">
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName" width="300">
        </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" width="450">
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <alter-button
              type="primary"
              size="small"
              @click="Edite(scope.$index, scope.row)"
              >编辑</alter-button
            >
            <alter-button
              type="danger"
              size="small"
              @click="Delete(scope.$index, scope.row), open()"
              >删除</alter-button
            >
            <alter-button
              @click.native.prevent="
                watch(scope.$index, scope.row), (assignForm = true)
              "
              type="warning"
              size="small"
              >分配权限
            </alter-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加角色表单 -->
    <div class="AddRoleFrame" v-show="formShow">
      <div class="form">
        <i class="el-icon-close" id="close" @click="close()"></i>
        <f-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <form-item label="角色名称" prop="roleName" class="roleName">
            <form-input
              v-model="ruleForm.roleName"
              name="roleName"
            ></form-input>
          </form-item>
          <form-item label="角色描述" prop="roleDesc">
            <form-input
              type="textarea"
              v-model="ruleForm.roleDesc"
              name="roleDesc"
              resize=none
            ></form-input>
          </form-item>
          <form-item class="roleBtn">
            <msg-button type="primary" @click="submitForm('ruleForm')"
              >添加</msg-button
            >
            <msg-button @click="resetForm('ruleForm')">重置</msg-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 编辑角色表单 -->
    <div class="AddRoleFrame" v-show="editeFormShow">
      <div class="editTable">
        <f-form
          ref="form"
          :model="sizeForm"
          label-width="80px"
          size="medium"
          class="editForm"
          @submit.native.prevent
        >
          <form-item label="角色名称" prop="roleName">
            <form-input
              v-model="sizeForm.roleName"
              name="roleName"
            ></form-input>
          </form-item>
          <form-item label="角色描述" prop="roleDesc">
            <form-input
              type="textarea"
              v-model="sizeForm.roleDesc"
              name="roleDesc"
              resize=none
            ></form-input>
          </form-item>
          <form-item size="large" class="roleBtn">
            <alter-button type="primary" @click="onSubmit()">修改</alter-button>
            <alter-button @click="cancle">取消</alter-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 分配权限表单 -->
    <div class="AddRoleFrame" v-show="assignForm">
      <div class="searchAssign">
        <div>分配权限</div>
        <el-divider></el-divider>
        <form-input placeholder="输入要搜索的权限名" v-model="filterAssign">
        </form-input>
        <el-tree
          class="filter-tree"
          show-checkbox
          :data="assignData"
          :props="defaultProps"
          node-key="resourceId"
          :default-checked-keys="defaultChecked"
          default-expand-all
          highlight-current
          :filter-node-method="filterNode"
          @check-change="handleCheckChange"
          ref="tree"
        >
        </el-tree>
        <div size="large" class="assignBtn">
          <alter-button @click="cancle">取消</alter-button>
          <alter-button type="primary" @click="assignSubmit()"
            >修改</alter-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import request from '@/api/utils/requery'
import {
  EditeRoleAPI,
  DeleteRoleAPI,
  WatchRoleAPI,
  WatchAllUserAPI,
  GetAllAuthorityAPI,
  EditeAuthorityAPI,
  DeleteAuthorityAPI
} from "@/api/utils";
export default {
  inject: ["reload"],
  data() {
    return {
      formShow: false,
      editeFormShow: false,
      ifRequest: true,
      assignForm: false,
      defaultChecked: [],
      filterAssign: "",
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      currentId: 0,
      currentDeleteId: 0,
      sizeForm: {
        roleName: "",
        roleDesc: "",
      },
      // 表单中的相关规则配置
      rules: {
        roleName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        roleDesc: [
          { required: true, message: "请填写角色描述", trigger: "blur" },
        ],
      },
      checked: false,
      checkedItem1: [],
      poJurisdiction: [],
      tableData: [],
      tags: [],
      // 权限修改的数组
      assignEditeArray: [],
      assignData: [],
      defaultProps: {
        children: "children",
        label: "resourceName",
        disabled: this.disabledFn,
      },
    };
  },
  methods: {
    // 关闭添加表单
    close() {
      this.formShow = false;
    },
    // 增加表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 提交添加表单
    submitForm(formName) {
      //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取所有的表单中的内容
          var params = $(".demo-ruleForm").serializeArray();
          //    console.log(params);
          //把从表单获取过来的值存储为对象
          let array = {};
          params.forEach((element) => {
            array[element.name] = element.value;
          });
          //把对象转换为 jsonp 格式
          array = JSON.stringify(array);
          request({
            method:'post',
            headers: {
              "Content-Type": "application/json",
            },
            url:`role/insert`,
            data: array,
          }).then(res=>{
            if (res.data.flag) {
              this.formShow = false;
              this.reload();
              this.$message.success("增加成功!");
            } else {
              this.$message.error("修改失败!");
            }
          })
        }
      });
    },
    //   编辑
    Edite(index, rows) {
      this.editeFormShow = true;
      this.sizeForm.roleName = rows.roleName;
      this.sizeForm.roleDesc = rows.roleDesc;
      this.currentId = rows.roleId;
    },
    // 编辑提交修改
    async onSubmit() {
      var params = $(".editForm").serializeArray();
      let array = {};
      array.roleId = this.currentId;
      //判断表单不能为空，且获取到数据
      params.forEach((element) => {
        if (element.value == "") {
          this.ifRequest = false;
          this.$message.error("表单不能为空！");
          this.reload();
        } else {
          // 把表单中获取到的值转化为对象形式
          array[element.name] = element.value;
        }
      });
      //把对象转换为 jsonp 格式
      if (this.ifRequest) {
        array = JSON.stringify(array);
        // console.log(array);
        // 进行修改操作
        return EditeRoleAPI(array).then((res) => {
          if (res.data.flag) {
            this.editeFormShow = false;
            this.reload();
            this.$message.success("修改成功！");
          } else {
            this.$message.error(response.data.errorMsg);
          }
        });
      }
    },
    // 取消编辑
    cancle() {
      this.editeFormShow = false;
      this.assignForm = false;
      this.$refs.tree.setCheckedKeys([]);
    },
    // 删除
    Delete(index, rows) {
      this.currentDeleteId = rows.roleId;
    },
    // 删除按钮判断
    open() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ExecuteDelete();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.reload();
        });
    },
    //执行删除操作
    async ExecuteDelete() {
      return DeleteRoleAPI(this.currentDeleteId).then((res) => {
        if (res.data.flag) {
          this.reload();
          this.$message.success("删除成功！");
        } else {
          this.$message.error("删除失败！");
        }
      });
    },
    // 过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.resourceName.indexOf(value) !== -1;
    },
    // 禁用已经有的权限
    disabledFn(v) {
      let index = this.defaultChecked.indexOf(v.resourceId);
      if (index != -1) {
        return true;
      }
    },
    // 查看权限
    async watch(index, rows) {
      this.currentId = rows.roleId;
      return WatchRoleAPI(this.currentId).then((res) => {
        if (res.data.flag) {
          res.data.data.forEach((el) => {
            this.defaultChecked.push(el.resourceId);
            this.defaultChecked = JSON.parse(
              JSON.stringify(this.defaultChecked)
            );
          });
        } else {
          this.$message.error("查询角色失败！");
        }
      });
    },
    handleCheckChange() {
      this.res = this.$refs.tree.getCheckedNodes(true, false);
    },
    // 提交权限修改
    async assignSubmit() {
      this.assignEditeArray = [];
      this.res.forEach((e) => {
        this.assignEditeArray.push(e.resourceId);
      });
      // 除去已经拥有的权限
      let index = 0;
      this.defaultChecked.forEach((el) => {
        index = this.assignEditeArray.indexOf(el);
        if (index !== -1) {
          this.assignEditeArray.splice(index, 1);
        }
      });
      return EditeAuthorityAPI(this.currentId,this.assignEditeArray).then(res=>{
        if (res.data.flag) {
          this.assignForm = false;
          this.reload();
          this.$message.success("分配权限成功!");
        } else {
          this.$message.error("分配权限失败!");
        }
      })
    },
    // 点击删除权限
    async handleClose(tag, rows) {
      let deteId = [];
      deteId.push(tag.resourceId);
      this.tableData[0].assign.splice(this.tableData[0].assign.indexOf(tag), 1);
      return DeleteAuthorityAPI(rows.roleId,deteId).then(res=>{
        if (res.data.flag) {
          // this.reload();
          this.$message.success("删除权限成功!");
          this.reload();
        } else {
          this.$message.error("删除权限失败!");
        }
      })
    },
  },
  async mounted() {
    const res = await WatchAllUserAPI();
    if (res.data.flag) {
      this.tableData = res.data.data;
    }
    this.tableData.forEach((e) => {
      request({
        method:'post',
        url:`resource/selectOne?roleId=${e.roleId}`
      }).then(res=>{
        if (res.data.flag) {
            e["assign"] = res.data.data;
          } else {
            this.$message.error("查询失败！");
          }
      })
    });
    const res2 = await GetAllAuthorityAPI()
     if (res2.data.flag) {
          let getAllassign = res2.data.data;
          // console.log(getAllassign);
          // 把获取过来的数组转换成可渲染的数组
          getAllassign.forEach((e) => {
            // console.log(e.resourceName,e.parentId.length);
            if (e.parentId == "-1") {
              e["children"] = [];
              this.assignData.push(e);
              // console.log(this.assignData);
            } else if (e.resourceId.length == 3) {
              this.assignData.forEach((element) => {
                if (element.resourceId === e.parentId) {
                  e["children"] = [];
                  element.children.push(e);
                }
              });
            } else if (e.resourceId.length == 6) {
              this.assignData.forEach((element) => {
                element.children.forEach((el) => {
                  if (el.resourceId === e.parentId) {
                    e["children"] = [];
                    el.children.push(e);
                  }
                });
              });
            } else {
              this.assignData.forEach((element) => {
                element.children.forEach((ele) => {
                  ele.children.forEach((el) => {
                    if (el.resourceId === e.parentId) {
                      el.children.push(e);
                    }
                  });
                });
              });
            }
          });
        }
  },
  watch: {
    filterAssign(val) {
      this.$refs.tree.filter(val);
    },
  },
};
</script>

<style scoped>
/* 增加表单的背景 */
.AddRoleFrame {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 98;
  background-color: rgba(0, 0, 0, 0.5);
}
/* 增加表单样式 */
.form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 580px;
  max-height: 650px;
  background-color: white;
  padding-left: 80px;
  padding-top: 30px;
  box-sizing: border-box;
  border-radius: 15px;
}
.form /deep/form input {
  margin: -3px;
}
.form /deep/.el-form demo-ruleForm {
  width: 450px;
  height: 500px;
}
.form /deep/.el-form-item__content {
  width: 300px;
}
/* 修改表单样式 */
.editTable,
.searchAssign {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 588px;
  max-height: 512px;
  padding: 10px 67px;
  background-color: white;
  border-radius: 10px;
  box-sizing: border-box;
  z-index: 99;
}
.editTable /deep/.el-input {
  width: 40%;
}
.editTable /deep/.el-textarea {
  width: 65%;
}
.roleBtn {
  margin-left: 35px;
}
#close {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  cursor: pointer;
  color: #ccc;
}
.CharacterBgc {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.ChaHeader {
  width: 100%;
  height: 60px;
}
.addCharactor {
  height: 40px;
}
.ChaContent {
  width: 100%;
  flex: 1;
}
.ChaContent /deep/.el-table .el-table__cell {
  padding: 15px 0;
}
.filter-tree {
  margin: 15px 0 60px 0;
}
.searchAssign {
  width: 500px;
  min-height: 350px;
  position: absolute;
}
.searchAssign /deep/.el-input {
  width: 55%;
}
.searchAssign /deep/.el-textarea {
  width: 65%;
}
.assignBtn {
  position: absolute;
  bottom: 18px;
  left: 32%;
}
.el-tag {
  margin: 0 18px;
}
.el-table--border {
  border: 3px solid #ebeef5;
}
.ChaContent /deep/.el-table .cell {
  color: #666;
}
.ChaContent /deep/.twoLineCls {
  color: black;
}
.ChaContent /deep/.el-table th.el-table__cell,
.ChaContent /deep/.el-table tr,
.ChaContent /deep/.el-table {
  background-color: rgba(255, 255, 255, 0.3);
}
</style>